<?php

class RM_Drupal_Model_Users extends RM_Users {

//TODO: Replace 'joomla_id' to 'drupal_id' or 'cms_id'
    public function createRow(array $data = array(), $defaultSource = null) {
        $cmsUser = RM_Environment::getConnector()->getUser();
        if ($cmsUser->isGuest() == false) {
            $data['cms_id'] = $cmsUser->getUser()->uid;
            if ($data['email'] != $cmsUser->getUser()->mail) {
                $result = $this->_save($data, false, true);
            }
        } else {
            $result = $this->_save($data, false, true);
        }
        return parent::createRow($data, $defaultSource);
    }

    public function insert($userDetails) {
        $cmsUser = RM_Environment::getConnector()->getUser();
        if (RM_Environment::getConnector()->getModule() != 'admin') {
            if ($cmsUser->isGuest() == false) {
                $userDetails['cms_id'] = $cmsUser->getUser()->uid;
                return parent::insert($userDetails);
            }
        }
        //$userDetails['id'] = 0; //for save users in db
        try {
            $cmsUserID = $this->_save($userDetails);
        } catch (RM_Exception $e) {
            throw $e;
        }

        $userDetails['cms_id'] = $cmsUserID;
        // parent special key command will resolve the insert function in the parent classes.
        // (IE: if not resolved in RM_Users, will go to parent class of RM_Users for resolution)
        return parent::insert($userDetails);
    }

    public function update($userDetails) {
        $joomlaUser = $this->_save($userDetails, true);
        $userDetails['cms_id'] = $joomlaUser;
        return parent::update($userDetails, "id='" . $userDetails['id'] . "'");
    }

// TODO: Return errors
    public function delete(array $ids) {
        $errors = array();
        foreach ($ids as $userID) {
            $coreModel = new RM_Users();
            $coreUser = $coreModel->find($userID)->current();
            $uid = $coreUser->cms_id;
            if ($uid) {
                user_delete($uid); //drupal function delete user
            }
            $coreUser->delete();
        }
    }

    //TODO: check user registration in drupal
    private function _checkConfig() {
        // If user registration is allowed then return true.
        $register = variable_get('user_register', 1);
        if ($register == 0) {
            return FALSE;
        } else {
            return TRUE;
        }
    }

    /**
     * Generates username using userdetails
     *
     * @param array $userDetails
     * @return string
     */
    private function _generateUsername($userDetails) {
        return $userDetails['first_name'] . '_' . time();
    }

    private function _save($userDetails, $updateOnly = false, $checkOnly = false) {
        if (!$this->_checkConfig()) {
            //return FALSE;
            throw new RM_Exception('Only site administrators can create new user accounts.');
        }

        if (isset($userDetails['cms_id'])) {
            $uid = $userDetails['cms_id'];
        } else {
            $uid = null;
        }

        $name = $userDetails['username'];
        $email = $userDetails['email'];

        if ($updateOnly && $uid != null) {
            $drupal_user = user_load($array = array('uid' => $uid)); //load user
        } else {
            $userDetails['id'] = 0;
            $drupal_user = '';
        }

        $account = array();
        $account['name'] = $userDetails['username'];
        $account['mail'] = $userDetails['email'];
        $account['pass'] = $userDetails['password'];
        $account['status'] = 1;

        if ($checkOnly) {
            $load_user_name = user_load($array = array('name' => $name));
            $load_user_mail = user_load($array = array('mail' => $email));

            if ($load_user_name->name != "" && $load_user_mail->mail != "") {
                throw new RM_Exception('User Name and Email Address already exist');
            } elseif ($load_user_name->name != "") {
                throw new RM_Exception('User Name already exist');
            } elseif ($load_user_mail->mail != "") {
                throw new RM_Exception('Email Address  already exist');
            } else {
                return TRUE;
            }
        }
// TODO: Get Drupal errors
        $new_user = user_save($drupal_user, $account); //save new user
        return $new_user->uid;
    }

}
